import {messages} from "share/common";
import React from 'react'
import { connect } from 'react-redux'


import { Form, Select, message, Button, Spin, Alert, Icon, Popconfirm } from 'antd'
const FormItem = Form.Item;
const Option = Select.Option;
import moment from 'moment';
import debounce from 'lodash.debounce'
import menuRoute from 'routes/menuRoute'


import AgencyRelation from 'containers/setting/agency-setting/agency-relation'
import agencyService from 'containers/setting/agency-setting/agency-setting.service'
import 'styles/setting/agency-setting/agency-detail.scss'

class AgencyDetail extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      pageLoading: false,
      data: [],
      principalOID: this.props.params.principalOID,
      principalValue: '',   //被代理人
      principalEditNum: 0,  //被代理人点击"修改"次数
      selectPrincipal: false,
      principalValidateStatus: '',  //被代理人校验
      principalHelp: '', //被代理人校验内容
      billProxyRuleDTOs: [],
      fetching: false,
      principalInfo: {},
      agencySetting:  menuRoute.getRouteItem('agency-setting','key'),    //代理设置
      agencyDetail:  menuRoute.getRouteItem('agency-detail','key'),    //代理详情
    };
    this.searchValue = debounce(this.searchValue, 250);
  }

  componentDidMount() {
    this.getInfo();
  }

  //获取被代理人及代理关系信息
  getInfo= () => {
    this.setState({ pageLoading: true });
    agencyService.getAgencyInfo(this.state.principalOID, this.props.location.query.tabKey).then(res =>{
      if (res.status === 200) {
        res = res.data;
        this.setState({
          pageLoading: false,
          principalValue: res.userName + ' - ' + res.emplyeeId,
          billProxyRuleDTOs: res.billProxyRuleDTOs,
          principalInfo: res
        })
      }
    }).catch(e => {
      this.setState({ pageLoading: false })
    })
  };

  //修改被代理人
  handleSave = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (err) {
        this.setState({
          principalValidateStatus: 'error',
          principalHelp: messages('common.please.select')//'请选择'
        });
        return;
      }
      if (this.state.principalValidateStatus !== 'error') {
        let principalObj = values[`principalObj-${this.state.principalEditNum}`];
        try {
          principalObj = JSON.parse(principalObj)
        } catch(e) {
          this.handleCancel();
          return;
        }
        values  = this.state.principalInfo;
        values.leavingDate = principalObj.leavingDate;
        values.status = principalObj.status;
        values.enabled = false;
        values.principalOID = principalObj.userOID;
        values.billProxyRuleDTOs = this.state.billProxyRuleDTOs;
        values.billProxyRuleDTOs.length > 0 && values.billProxyRuleDTOs.map(item => { item.customFormDTOs=[] });
        this.setState({loading: true});

        agencyService.newAgency(values).then(res => {
          this.setState({
            loading: false,
            selectPrincipal:false,
            principalOID: res.data.principalOID
          }, () => {
            this.getInfo();
            message.success(messages('common.save.success', {name: ''}));
            this.context.router.push(this.state.agencyDetail.url.replace(':principalOID', this.state.principalOID) + `?tab=${this.props.location.query.tab}`);
          });
        }).catch(e => {
          this.setState({loading: false});
          message.error(`${messages('common.save.filed')}, ${e.response.data.message}`)
        })
      }
    });
  };

  handleChange = (value) => {
    if (!value) {
      this.setState({
        principalValidateStatus: 'error',
        principalHelp: messages('common.please.select')
      })
    }
  };

  //查询被代理人下拉列表
  handleSearch = (value, id) => {
    let principalInfo = this.props.form.getFieldValue(`principalObj-${this.state.principalEditNum}`);
    if (!value && principalInfo && !this.state.data.length) {
      try {
        if (typeof JSON.parse(principalInfo) === 'object') {
          this.setState({ data: [JSON.parse(principalInfo)], fetching: false })
        }
      } catch(e) {
        this.setState({ fetching: false })
      }
    }
    this.searchValue(value);
  };

  searchValue = (value) => {
    const { tab } = this.props.location.query;
    value && this.setState({
      principalValidateStatus: '',
      principalHelp: '',
      fetching: true
    });
    let params = {
      page: 0,
      size: 1000,
      keyword: value
    };
    params.status = tab === 'apply' ? undefined : 'all'; //undefined为不传status参数，查出的为在职和待离职人员
    value && agencyService.getPersonByValueV2(params).then((response) => {
      let resultData = [];
      let data = response.data;
      data.map(item => {
        item.text = `${item.fullName} ${item.firstName} ${item.lastName} - ${item.employeeID}`;
        //只支持工号和姓名搜索，手机和邮箱要去除
        if (item.text.indexOf(value.toLowerCase()) > -1 || item.text.indexOf(value.toUpperCase()) > -1) {
          resultData.push(item);
        }
      });
      this.setState({ data: resultData, fetching: false });
    });
  };

  //选中被代理人后查询该被代理人状态（是否已存在、是否将离职）
  handleSelect = (values) => {
    let principalInfo = JSON.parse(values);
    principalInfo.userOID && agencyService.getPersonStatusByOid(principalInfo.userOID, this.props.location.query.tabKey).then((response)=>{
      let leaveTime = moment(principalInfo.leavingDate).format('YYYY-MM-DD');
      if (response.data) {
        this.setState({
          principalValidateStatus: 'error',
          principalHelp: messages('setting.key1'/*此员工已存在被代理信息，请返回至前一页面搜索该员工并编辑*/)        })
      } else {
        if (principalInfo.status === 1002) {
          this.setState({
            principalValidateStatus: 'warning',
            principalHelp: `${messages('setting.key1433',{arg1: leaveTime}/*该员工将于 {arg1} 离职*/)} ${
              this.props.location.query.tab === 'apply' ? messages('setting.key2'/*，离职后此代理将自动禁用*/) : ''}`
          })
        } else if (principalInfo.status === 1003) {
          this.setState({
            principalValidateStatus: 'warning',
            principalHelp: messages('setting.key1434',{arg1: leaveTime}/*该员工已于 {arg1} 离职*/)
          })
        } else {
          this.setState({
            principalValidateStatus: '',
            principalHelp: ''
          })
        }
      }
    });
  };

  //取消新建代理
  handleCancel = () => {
    this.setState({ selectPrincipal: false })
  };

  //修改代理人
  toSelectPrincipal = () => {
    let principalEditNum = this.state.principalEditNum ++;
    this.setState({
      selectPrincipal: true,
      principalEditNum
    })
  };

  //返回
  handleBack = () => {
    this.context.router.replace(this.state.agencySetting.url + `?tab=${this.props.location.query.tab}`);
  };

  render(){
    const { getFieldDecorator } = this.props.form;
    const { loading, pageLoading, data, principalOID, principalValue, selectPrincipal, principalEditNum , principalValidateStatus, principalHelp,
            billProxyRuleDTOs, principalInfo, fetching } = this.state;
    const options = data.map(d => <Option key={JSON.stringify(d)}>{d.text}</Option>);
    let principalItem;
    let saveBtn;
    if (selectPrincipal) {  //选择被代理人
      principalItem = (
        <FormItem colon={false}
                  validateStatus={principalValidateStatus}
                  help={principalHelp}
                  className="principal-item"
                  >
          {getFieldDecorator(`principalObj-${principalEditNum}`, {
            rules: [{
              required: true,
              message: messages('common.please.select')
            }],
            initialValue: principalValue
          })(
            <Select placeholder={messages('setting.key6'/*请输入姓名/工号*/)}
                    showSearch
                    allowClear
                    filterOption={false}
                    notFoundContent={fetching ? <Spin size="small" /> : messages('setting.key7'/*无匹配结果*/)}
                    onChange={this.handleChange}
                    onSearch={value => this.handleSearch(value, `principalObj-${principalEditNum}`)}
                    onSelect={this.handleSelect}
                    getPopupContainer={triggerNode => triggerNode.parentNode}>
              {options}
            </Select>
          )}
        </FormItem>
      );
      saveBtn = (
        <FormItem>
          <Popconfirm placement="bottomLeft"
                      title={messages('setting.key8'/*被代理人修改后，代理关系中的代理单据将被清空*/)}
                      onConfirm={this.handleSave}>
            <Button type="primary"
                    loading={loading}
                    style={{marginRight:'10px'}}>{messages('common.save')}</Button>
          </Popconfirm>
          <Button onClick={this.handleCancel}>{messages('common.cancel')}</Button>
        </FormItem>
      )
    } else {  //新建代理关系
      principalItem = (
        <FormItem>
          <div style={{fontSize:'14px'}}>
            <span style={{color:'#333'}}>{messages('common.has.selected')}：</span>
            <span style={{fontSize:'20px',color:'#000'}}>{principalValue}</span>
            <a className='default-color-font' style={{marginLeft:'20px'}} onClick={this.toSelectPrincipal}>{messages('common.edit')}</a>
          </div>
        </FormItem>
      );
      saveBtn = ""
    }
    let alertMessage;
    let leaveTime = moment(principalInfo.leavingDate).format("YYYY-MM-DD");
    if(principalInfo.status === 1003) {
      alertMessage = (
        <Alert message={messages('setting.key9'/*请注意*/)}
               description={`${messages('setting.key1435',{arg1: principalInfo.userName,arg2: principalInfo.emplyeeId,arg3: leaveTime}/*员工 {arg1}-{arg2} 已于 {arg3} 日离职*/)}
                 ${this.props.location.query.tab === 'apply' ? messages('setting.key10'/*，代理关系已于该日期内自动禁用*/) : ''}`}
               type="warning"
               showIcon
               style={{marginBottom:'20px'}}/>
      )
    } else if (principalInfo.status === 1002) {
      alertMessage = (
        <Alert message={messages('setting.key9'/*请注意*/)}
               description={`${messages('setting.key1436',{arg1: principalInfo.userName,arg2: principalInfo.emplyeeId,arg3: leaveTime}/*员工 {arg1}-{arg2} 将于 {arg3} 日离职*/)}
                 ${this.props.location.query.tab === 'apply' ? messages('setting.key11'/*，代理关系将于该日期内自动禁用*/) : ''}`}
               type="warning"
               showIcon
               style={{marginBottom:'20px'}}/>
      )
    } else {
      alertMessage = ""
    }
    return (
      <div className="agency-detail">
        <Spin spinning={pageLoading}>
          {alertMessage}
          <h3 className="header-title">{messages('setting.key3'/*被代理人*/)}</h3>
          <p className="header-info" style={{color:"#999"}}>
            {this.props.location.query.tab === 'apply' ?
              messages('setting.key4'/*需要他人帮助其填写、提交相应单据的人*/) :
              this.props.location.query.tab === 'approve' ?
              messages('setting.key5'/*需要他人帮助其审批相应单据的人*/):
              messages('setting.key2835'/*需要他人帮助操作账本及消费记录*/)}
          </p>
          <Form>
            {principalItem}
            {saveBtn}
          </Form>
          <AgencyRelation principalOID={principalOID}
                          billProxyRuleDTOs={billProxyRuleDTOs}
                          principalInfo={principalInfo}
                          tab={this.props.location.query.tab}
                          tabKey={this.props.location.query.tabKey}/>
                          
        </Spin>
        <a className="back-icon" onClick={this.handleBack}>
          <Icon type="rollback" />{messages('common.back')}
        </a>
      </div>
    )
  }

}


AgencyDetail.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps() {
  return {}
}

const WrappedAgencyDetail = Form.create()(AgencyDetail);

export default connect(mapStateToProps)(WrappedAgencyDetail);
